import { createRouter, createWebHistory } from 'vue-router'

import NProgress from 'nprogress' // 导入 nprogress模块

import 'nprogress/nprogress.css' // 导入样式，否则看不到效果
import localStorage from '@/utils/local-storage'
import { loading } from '@/utils/loading'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/login.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/main.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/not-found/not-found.vue')
    }
  ]
})

router.beforeEach((to) => {
  console.log(to.path)
  NProgress.configure({ showSpinner: false })
  NProgress.start() //开启进度条
  console.log('eee')
  if (!(window as any).existLoading) {
    console.log('eeee')
    loading.show()
    ;(window as any).existLoading = true
  }
  if (to.path !== '/login') {
    const token = localStorage.get('token')
    if (!token) {
      return '/login'
    }
    if (to.path === '/main') {
      return router.getRoutes()[0].path
    }
  }
})

// 路由加载后
router.afterEach((to) => {
  console.log(to.path)
  console.log('eeeee')
  if ((window as any).existLoading) {
    console.log('eeeeee')
    loading.hide()
  }
  NProgress.done() //完成进度条
})
export default router
